package com.leetcode.No0160;

import org.junit.Test;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 *
 * @program: leetcode
 * @description: 相较链表
 * 什么破题！
 * @author: wangzhihua
 * @date: 2021-07-24
 */
public class Solution02 {

	@Test
	public void test01() {
		int[] nums1 = new int[]{4, 1, 8, 4, 5};
		int[] nums2 = new int[]{5, 0, 1, 8, 4, 5};
		System.out.println(createNodes(nums1));
		System.out.println(createNodes(nums2));
		System.out.println(getIntersectionNode(createNodes(nums1), createNodes(nums2)));
		System.out.println("====================================");

		int[] nums3 = new int[]{0, 9, 1, 2, 4};
		int[] nums4 = new int[]{3, 2, 4};
		System.out.println(createNodes(nums3));
		System.out.println(createNodes(nums4));
		System.out.println(getIntersectionNode(createNodes(nums3), createNodes(nums4)));
		System.out.println("====================================");
	}

	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		ListNode a = headA;
		ListNode b = headB;
		while (a != b) {
			a = (a == null ? headB : a.next);
			b = (b == null ? headA : b.next);
		}
		return a;

	}

	public ListNode createNodes(int[] nums) {
		ListNode nextNode = null;
		ListNode headNode = null;
		for (int i = nums.length - 1; i >= 0; --i) {
			headNode = new ListNode(nums[i]);
			headNode.next = nextNode;
			nextNode = headNode;
		}
		return headNode;
	}

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}

		@Override
		public String toString() {
			return val + (next == null ? "" : " -> " + next.toString());
		}
	}

}
